package com.snail.study.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 网络传输数据（阻塞式IO），服务端给客户端反馈
 * @author tim
 * @since 2021/3/30
 */
public class BlockNio2Test {

    @Test
    public void client(){
        try {
            SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));
            FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (inChannel.read(buffer) != -1){
                buffer.flip();
                socketChannel.write(buffer);
                buffer.clear();
            }
            socketChannel.shutdownOutput();

            //接受服务端发送的信息
            int len;
            while ((len = socketChannel.read(buffer)) != -1){
                buffer.flip();
                System.out.println(new String(buffer.array(),0,len));
                buffer.clear();
            }

            socketChannel.close();
            inChannel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void server(){
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

            serverSocketChannel.bind(new InetSocketAddress(9898));
            SocketChannel socketChannel = serverSocketChannel.accept();
            FileChannel outChannel = FileChannel.open(Paths.get("3.jpg"),StandardOpenOption.WRITE,StandardOpenOption.CREATE);
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (socketChannel.read(buffer) != -1){
                buffer.flip();
                outChannel.write(buffer);
                buffer.clear();
            }

            //服务端接受完成向客户端发送信息
            buffer.put("服务端接受数据完成".getBytes());
            buffer.flip();
            socketChannel.write(buffer);

            socketChannel.close();
            serverSocketChannel.close();
            outChannel.close();

        }catch (IOException e){
            System.out.println(e.getMessage());
        }
    }

}
